package com.passcheck.anno;

import cn.hutool.json.JSONUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 日志AOP
 */
@Aspect
@Order(1)
@Component
public class LogAspect {

    public Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 切入点
     */
    @Pointcut(value = "execution(public * com.passcheck.controller..*.*(..))")
    public void controllerAspect(){
    }

    /**
     * 请求method前打印内容
     * @param joinPoint
     */
    @Before(value = "controllerAspect()")
    public void methodBefore(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //打印请求内容
        logger.info("===============请求内容===============");
        logger.info("请求地址:"+request.getRequestURL().toString());
        logger.info("请求方式:"+request.getMethod());
        logger.info("请求类方法:"+joinPoint.getSignature());
        logger.info("请求类方法参数:"+ Arrays.toString(joinPoint.getArgs()));
        logger.info("===============请求内容===============");
    }

    @AfterReturning(returning = "o",pointcut = "controllerAspect()")
    public void methodAfterReturing(Object o ){
        logger.info("--------------返回内容----------------");
        logger.info("Response内容:"+ JSONUtil.toJsonStr(o));
        logger.info("--------------返回内容----------------");
    }
}
